package dao

import (
	userApi "mldong/api/user"
	"mldong/internal/modules/sys/entity"

	"mldong/utility"

	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gtime"
)

type UserDao struct {
}

// 插入用户信息
func (u *UserDao) Insert(entity entity.User, tx gdb.TX) (res entity.User, _ error) {
	var now = gtime.Now()
	entity.CreateTime = now
	entity.UpdateTime = now
	if entity.ID == nil {
		entity.ID = utility.GenId()
	}
	var _, err = u.Model(tx).Data(entity).Insert()
	return entity, err
}

// 更新用户信息
func (u *UserDao) UpdateById(entity entity.User, tx gdb.TX) (count int64, _ error) {
	var now = gtime.Now()
	entity.UpdateTime = now

	var result, err = u.Model(tx).Data(entity).Where(
		"id=?", entity.ID,
	).Update()
	count, _ = result.RowsAffected()
	return count, err
}

// 根据用户ID删除
func (u *UserDao) DeleteById(id string, tx gdb.TX) (count int64, _ error) {
	var now = gtime.Now()
	// g.Model("sys_user").Where("id=?", id).Delete()
	var result, err = u.Model(tx).Data(g.Map{
		"is_deleted":  1,
		"update_time": now,
	}).Where("id=?", id).Update()
	if err != nil {
		return 0, err
	}
	count, _ = result.RowsAffected()
	return count, nil
}

// 根据用户IDS删除
func (u *UserDao) DeleteByIds(ids []string) (count int64, _ error) {
	var now = gtime.Now()
	// g.Model("sys_user").WhereIn("id", ids).Delete()
	var result, err = g.Model("sys_user").Data(g.Map{
		"is_deleted":  1,
		"update_time": now,
	}).WhereIn("id", ids).Update()
	if err != nil {
		return 0, err
	}
	count, _ = result.RowsAffected()
	return count, nil
}

// 根据ID获取用户信息
func (u *UserDao) GetById(id string) (res entity.User, err error) {
	err = g.Model("sys_user").Where("id=?", id).Where("is_deleted=?", 0).Scan(&res)
	return res, err
}

// 分页获取用户信息
func (u *UserDao) Page(pageNum int, pageSize int, modelHandler func(m *gdb.Model) *gdb.Model) (users []userApi.UserVO, total int, err error) {
	var model = g.Model("sys_user t")
	model = model.Fields("t.*", "d.name as dept_name", "p.name as post_name", "d.code as dept_code", "p.code as post_code")
	model = model.LeftJoin("sys_dept d", "d.id=t.dept_id")
	model = model.LeftJoin("sys_post p", "p.id=t.post_id")
	// 允许外部修改 model
	if modelHandler != nil {
		model = modelHandler(model)
	}
	model = model.Where("t.is_deleted=?", 0)
	err = model.Page(pageNum, pageSize).ScanAndCount(&users, &total, false)
	return users, total, err
}

// 根据用户名获取用户信息
func (u *UserDao) GetByUserName(userName string) (res entity.User, err error) {
	err = g.Model("sys_user").Where("user_name=?", userName).Where("is_deleted=?", 0).Scan(&res)
	return res, err
}

// 获取sys_user模型
func (u *UserDao) Model(tx gdb.TX) *gdb.Model {
	var model *gdb.Model
	if tx != nil {
		model = tx.Model("sys_user")
	} else {
		model = g.Model("sys_user")
	}
	return model
}
func NewUserDao() *UserDao {
	return &UserDao{}
}
